import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Divider } from 'antd';
import React, { useState, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { ActionType, ProColumns } from '@ant-design/pro-table/lib/Table.d';

import { SorterResult } from 'antd/es/table/interface';

import CreateForm from './components/CreateForm';
import MemberModal from './components/MemberModal';
import { Category, CategoryType } from './data.d';
import { queryRule, removeRule, addRule, updateRule } from './service';
import { arrToTree } from '@/utils/utils';
import { CategorySelect } from '@/components/Category';

/**
 * 添加节点
 * @param fields
 */
const handle = async (fields: Category, id: any) => {
  const isAdd = !id;
  const txt = isAdd ? '添加' : '编辑';
  const hide = message.loading(`正在${txt}`);
  const params = { ...fields };
  Object.assign(params, { type: CategoryType.ADMIN });
  try {
    if (isAdd) {
      await addRule(params);
    } else {
      await updateRule(id, params)
    }
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error(`${txt}失败请重试！`);
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (id: number) => {
  const hide = message.loading('正在删除');
  try {
    await removeRule({ id });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const [sorter, setSorter] = useState<string>('');
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [memberGroupId, setMemberGroupId] = useState('');
  const [stepFormValues, setStepFormValues] = useState<Category>();
  const actionRef = useRef<ActionType>();
  const [refresh, setRefresh] = useState({});

  function renderMemberModal() {
    if (!memberGroupId) {
      return '';
    }
    return (
      <MemberModal
        onCancel={() => {
          setMemberGroupId('');
        }}
        onOk={() => {
          setMemberGroupId('');
          // reloadAuthInfo();
        }}
        groupId={memberGroupId}
        visible
      />
    );
  }

  const columns: ProColumns<Category>[] = [
    {
      title: '分类名称',
      dataIndex: 'name',
      rules: [
        {
          required: true,
          message: '分类名称为必填项',
        },
      ],
      labelCol: { span: 6 },
      initialValue: stepFormValues?.name,
    },
    {
      title: '描述',
      dataIndex: 'desc',
      rules: [
        {
          required: true,
          message: '描述为必填项',
        },
      ],
      labelCol: { span: 6 },
      initialValue: stepFormValues?.desc,
      render: (v) => v || '-',
    },
    {
      title: '上级',
      dataIndex: 'pid',
      hideInTable: true,
      renderFormItem: (item: ProColumns<Category>, record: any) => {
        return <CategorySelect
          value={record.value}
          placeholder="请选择分类"
        />
      },
      labelCol: { span: 6 },
      initialValue: `${stepFormValues?.pid || ''}`,
      render: (v) => v || '-',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              setStepFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={async () => {
              await handleRemove(record.id);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<Category>
        headerTitle="商品后台分类"
        actionRef={actionRef}
        rowKey="id"
        pagination={false}
        search={false}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<Category>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              setStepFormValues();
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          const { data } = await queryRule();
          return {
            data: arrToTree<Category>(data.list),
            total: data.list.length
          }
        }}
        columns={columns}
        rowSelection={{}}
      />
      <CreateForm
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        id={stepFormValues?.id}
      >
        <ProTable<Category, Category>
          onSubmit={async (value: Category) => {
            const success = await handle(value, stepFormValues?.id);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="key"
          type="form"
          columns={columns}
          rowSelection={{}}
        />
      </CreateForm>
      {renderMemberModal()}
    </PageHeaderWrapper>
  );
};

export default TableList;
